package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */

/*任务8 手机验证码登录 肖丁豪*/
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map param, HttpServletRequest request) {
        //根据键找手机号、验证码的值
        String telephone = param.get("telephone").toString();
        String validateCode = param.get("validateCode").toString();
        //创建key
        String key = RedisConst.VALIDATE_CODE_PREFIX +"_MOBILE_SIGNIN_"+telephone;
        //从redis获取用户上传的验证码
        String code = redisTemplate.opsForValue().get(key).toString();
        //判断是否输入正确
        if (!StringUtils.isEmpty(code) && code.equals(validateCode)) {
            //输入正确 删除redis释放资源
            redisTemplate.delete(key);
            //创建用户
            Member member = new Member();
            member.setPhoneNumber(telephone);
            member = memberService.createOrUpdate(member);
            request.getSession().setAttribute("member", member);
            //模拟登陆成功
            log.info("登录成功，id是：{}", member.getId());
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        } else {
            //验证码输入错误登陆失败
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
    }
}
